<template>
    <div class="xui-upload">
        <input class="xui-upload-input" ref="fileInput" type="file" @change="onFileChange" multiple />
        <input class="xui-upload-input" ref="fileDirInput" type="file" @change="onDirChange" multiple webkitdirectory />
        <div class="xui-select-upload-file" @click="uploadSelect">
            <h4>选择上传文件</h4>
        </div>
        <div class="xui-upload-files">
            <ul v-if="fileList">
                <li v-for="(it, i) in fileList" :key="i">
                    {{it.name}} / {{it.up_info}}
                </li>
            </ul>
            <button @click="upload">开始上传</button>
        </div>        
    </div>
</template>
<script lang="ts">
import { ref } from 'vue'
import type { UploadFileInfo } from './type'
import HttpClient  from '/@/utils/HttpClient'
const client = new HttpClient({})
export default {
    props: {
        url: {
            type: String,
            default: () => ("")
        }
    },
    setup(props, context) {
        const fileInput = ref<HTMLInputElement>()
        const fileDirInput = ref<HTMLInputElement>()
        const fileList = ref<UploadFileInfo[]>([])
        return {
            fileInput,
            fileDirInput,
            fileList
        }
    },
    methods: {
        uploadSelect () {
            if(this.fileInput)
                this.fileInput.click()
        },
        onDirChange (e:Event) {

        },
        onFileChange (e:Event) {
            let target = e.target as HTMLInputElement
            if(target.files) {
                let len = target.files.length
                for (let i = 0; i < len; i++){
                    let it = target.files[i]
                    this.fileList.push({name: it.name, dir: '', size: it.size, file: it})
                }
            }            
            console.log(target.files)
        },
        upload () {
            for(let i in this.fileList) {
                let it = this.fileList[i]
                this.uploadItem(it)
            }
        },
        uploadItem(item:UploadFileInfo) {
            let upload_url = this.url           
            if(item.dir) {
                upload_url = `${upload_url}?dir=${item.dir}`
            }
            return client.uploadFile({url: upload_url,  onUploadProgress: e=>{
                item.up_info = e.progress + ""
                console.log(e)
            }}, {
                name: "files",
                file: item.file
            })
        }
    }
}





</script>
<style lang="scss" scoped>
    .xui-upload {
        .xui-upload-input {
            display: none;
        }
        .xui-select-upload-file {
            text-align: center;
            border: dashed 1px #ccc;
            border-radius: 10px;
            padding: 1em;
        }
    }
</style>